package com.example.lettcode._202412._20241212;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
387. 字符串中的第一个唯一字符
给定一个字符串 s ，找到 它的第一个不重复的字符，并返回它的索引 。如果不存在，则返回 -1 。

示例 1：
输入: s = "leetcode"
输出: 0

示例 2:
输入: s = "loveleetcode"
输出: 2

示例 3:
输入: s = "aabb"
输出: -1

提示:
1 <= s.length <= 105
s 只包含小写字母
 */
public class _387_di_yi_ge_wei_yi_zi_fu {
    public static void main(String[] args) {
        String s = "loveleetcode";
        System.out.println(firstUniqChar2(s));
    }

    public static int firstUniqChar(String s) {
        char[] chars = s.toCharArray();

        for (int i = 0; i < chars.length-1; i++) {
            char c = s.charAt(i);
            s.replace(c, ' ');
            s.lastIndexOf(String.valueOf(c));
            String temps = s.substring(i + 1);
            if (temps.indexOf(String.valueOf(c)) == -1) {
                return i;
            }
        }
        return -1;
    }

    public static int firstUniqChar2(String s) {
        Map<Character, Integer> map = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            char aChar = s.charAt(i);
            if (map.containsKey(aChar)) {
                map.put(aChar, 2);
            } else {
                map.put(aChar, 1);
            }
        }

        for (int i = 0; i < s.length(); i++) {
            if (map.get(s.charAt(i)) == 1) {
                return i;
            }
        }

        return -1;
    }

    public static int firstUniqChar3(String s) {
        int[] tempI = new int[26];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            tempI[c - 'a']++;
        }

        for (int i = 0; i < s.length(); i++) {
            if (tempI[s.charAt(i) - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }

    public static int firstUniqChar4(String s) {
        char[] chars = s.toCharArray();
        int[] tempI = new int[26];
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            tempI[c - 'a']++;
        }

        for (int i = 0; i < chars.length; i++) {
            if (tempI[chars[i] - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }
}
